<!--历史数据-->
<template>
  <div class="ele-body">
    <!-- 搜索表单 -->
    <div class="block-interval">
      <a-card :bordered="false">
        <a-form layout="inline" :model="where">
          <a-row>
            <a-form-item label="开始时间:">
              <a-date-picker v-model:value="where.searchBeginTime" type="date" show-time format="YYYY-MM-DD HH:mm:ss" valueFormat="YYYY-MM-DD HH:mm:ss" />
            </a-form-item>
            <a-form-item label="结束时间:">
              <a-date-picker v-model:value="where.searchEndTime" type="date" show-time format="YYYY-MM-DD HH:mm:ss" valueFormat="YYYY-MM-DD HH:mm:ss" />
            </a-form-item>
            <a-form-item class="ele-text-center">
              <a-space>
                <a-button type="primary" @click="reload">查询</a-button>
                <a-button @click="reset">重置</a-button>
              </a-space>
            </a-form-item>

          </a-row>
        </a-form>
      </a-card>

      <a-card
        :bordered="false"
        :body-style="{padding: '16px 6px 0 0'}">
        <v-chart
          ref="ch4Chart"
          style="height: 550px;"
          :option="methaneChartOption"/>
      </a-card>
    </div>

    <!-- 表格 -->
    <div>
      <a-card :bordered="false">
        <ele-pro-table
          ref="table"
          row-key="dlwpdId"
          :datasource="datasource"
          :columns="columns"
          :where="where"
          v-model:selection="selection"
          :scroll="{ x: 'max-content' }"
        >
          <template #bodyCell="{ column, record }">
            <!-- table操作栏按钮 -->
            <template v-if="column.key === 'action'">
              <a-space>
                <!--<a @click="openDetail(record)">详情</a>-->
                <!--<a-divider type="vertical" />-->
                <a-popconfirm title="确定要删除此记录吗？" @confirm="remove(record)">
                 <a class="ele-text-danger">删除</a>
                </a-popconfirm>
              </a-space>
            </template>
          </template>
          <template #expandedRowRender="{ column, record }">
            <a-table :columns="innerColumns" :data-source="formatInnerTab(record.content)" :pagination="false" />
          </template>
        </ele-pro-table>
      </a-card>
    </div>

   <!-- 编辑弹窗 -->
    <DeviceLuoxunPulsationDataDetail v-if="showDetail" v-model:visible="showDetail" :data="current"/>
  </div>
</template>

<script>
import { provide } from 'vue';
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { LineChart, BarChart } from 'echarts/charts';
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
  DataZoomComponent
} from 'echarts/components';
import VChart, { THEME_KEY } from 'vue-echarts';
import 'echarts-wordcloud';
import { ChartTheme } from 'ele-admin-pro';
import { DeviceLuoxunPulsationDataApi } from '@/api/property/DeviceLuoxunPulsationDataApi';
import DeviceLuoxunPulsationDataDetail from './luoxunpulsation-data-detail.vue';
import { message } from 'ant-design-vue';
import moment from "moment";

use([
  CanvasRenderer,
  LineChart,
  BarChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  DataZoomComponent
]);

provide(THEME_KEY, ChartTheme);

export default {
  name: 'DeviceLuoxunPulsationData',
  components: {
    DeviceLuoxunPulsationDataDetail,
    VChart,
  },
  props: {
    data: Object
  },
  async mounted() {
    this.getNewData();
  },
  computed: {
    methaneChartOption(){
      return {
        tooltip: {
          trigger: 'axis',
          formatter:function(params){ // 改鼠标悬浮提示值格式
            console.log(params);
            if (params.length > 1) {
              let relVal = "第" + params[0].name + "点<br/>";
              relVal = relVal + params[0].data.date +"<br/>";
              relVal += params[0].seriesName+ ' : ' + (-params[0].value) +"<br/>";
              relVal += params[1].seriesName+ ' : ' + (-params[1].value)+"<br/>";
              return relVal;
            } else if (params.length > 0) {
              let relVal = "第" + params[0].name + "点<br/>";
              relVal = relVal + params[0].data.date +"<br/>";
              relVal += params[0].seriesName+ ' : ' + (-params[0].value);
              return relVal;
            }

          }
        },
        legend: {
          data: ['通道A(kpa)', '通道B(kpa)'],
          right: 20
        },
        xAxis: [
          {
            name : "closed",
            type: 'category',
            nameLocation : 'start',
            data : this.plusationContent.xaxis,
            nameTextStyle : {
              color : 'red',
              fontWeight : 'bold',
              fontSize : '15'
            }
          },
        ],
        yAxis:[
          {
            type: 'value',
            show : true,
            max : 127,
            name : "(kpa)open",
            nameTextStyle : {
              color : 'green',
              fontWeight : 'bold',
              fontSize : '15'
            },
            axisLabel:{
              show : true,
              formatter : function(value){
                if (value == 0) {
                  return '';
                } else
                  return -value;
              },
            },
            axisTick : {
              show : true
            },
            interval: 15,   // 刻度
            min: -127,
            smooth: true // 平滑曲线
          },
        ],
        series: [
          {
            name: '通道A(kpa)',
            type: 'line',
            smooth: true,
            data: this.plusationContent.a,
          },
          {
            name: '通道B(kpa)',
            type: 'line',
            smooth: true,
            data: this.plusationContent.b,
          }
        ],
        // dataZoom: [{
        //   show: true,
        //   type: 'inside',
        //   filterMode: 'none',
        // }],
      }
    }
  },
  data() {
    return {
      // 表格列配置
      columns: [
        {
          title: '时间',
          dataIndex: 'createTime'
        },
        {
          title: '采样数据序号',
          dataIndex: 'dataSerial'
        },
        {
          title: '操作',
          key: 'action',
          width: 280,
          align: 'center'
        }
      ],
      innerColumns : [
        {
          title: '3s内采样点',
          dataIndex: 'no'
        },
        {
          title: 'A通道数据(kpa)',
          dataIndex: 'a'
        },
        {
          title: 'B通道数据(kpa)',
          dataIndex: 'b'
        },
      ],
      // 表格搜索条件
      where: {"recordId" : this.data.recordId},
      // 表格选中数据
      selection: [],
      // 当前编辑数据
      current: null,
      // 是否显示编辑弹窗
      showDetail: false,
      plusationContent : {},
    }
  },
  methods: {
    getNewData() {
      let that = this;
      let params =  {
        "recordId" : that.data.recordId,
        "orderBy" : "ASC",
        "sortBy" : "upload_time",
        searchBeginTime : moment().subtract(1, 'h').format('YYYY-MM-DD HH:mm:ss'),
        searchEndTime : moment().format('YYYY-MM-DD HH:mm:ss'),
      };

      if (this.where.searchBeginTime && this.where.searchEndTime) {
        params.searchBeginTime = this.where.searchBeginTime;
        params.searchEndTime = this.where.searchEndTime;
      }

      DeviceLuoxunPulsationDataApi.list(params).then(result => {
        let rows = result.data || [];
        console.log(rows);
        let serialsA = [];
        let serialsB = [];
        let xaxisData = [];
        if (rows.length > 0) {
          for (let i = 0, len = rows.length; i < len; i++) {
            let plusationResultContent = JSON.parse((rows[i].content || "[]"));
            console.log(plusationResultContent);
            if (plusationResultContent.length > 0) {
              plusationResultContent.forEach(function (item){
                let aItem = {
                  'date' : rows[i].uploadTime,
                  'value' : -1 * item.a
                };
                let bItem = {
                  'date' : rows[i].uploadTime,
                  'value' : -1 * item.b
                };
                serialsA.push(aItem);
                serialsB.push(bItem);
              });
            }
          }
          console.log(serialsA.length);
          console.log(serialsB.length);
        }
        if (serialsA.length > 0) {
          for (let i = 1; i <= serialsA.length; i++) {
            xaxisData.push(i);
          }
        }
        that.plusationContent = {
          a : serialsA,
          b : serialsB,
          xaxis : xaxisData,
        };
      });
    },
    formatInnerTab(content){
      let formatDatas = [];
      let plusationResultContent = JSON.parse((content || "[]"));
      if (plusationResultContent.length > 0) {
        for (let i = 0; i < plusationResultContent.length; i++) {
          formatDatas.push({
            "no" : "第" + (i+1) + "次采样",
            "a" : plusationResultContent[i].a,
            "b" : plusationResultContent[i].b,
          });
        }
      }
      return formatDatas;
    },
    /**
     * 搜索按钮
     *
     * @author cancan
     * @date 2022/03/05 14:48
     */
    reload() {
      this.selection = [];
      this.$refs.table.reload({ page: 1 });
      this.getNewData();
    },

    /**
     * 重置搜索
     *
     * @author cancan
     * @date 2022/03/05 14:48
     */
    reset() {
      this.where.recordId = this.data.recordId;
      this.where.searchBeginTime = '';
      this.where.searchEndTime = '';
      this.$nextTick(() => {
        this.reload();
      });
    },

    /**
     * 删除
     *
     * @author cancan
     * @date 2022/03/05 14:48
     */
    async remove(row) {
      const result = await DeviceLuoxunPulsationDataApi.delete({ dlgdId: row.dlgdId });
      message.success(result.message);
      this.reload();
    },

    /**
     * 打开新增或编辑弹窗
     *
     * @author cancan
     * @date 2022/03/05 14:48
     */
    openDetail(row) {
      this.current = row;
      this.showDetail = true;
    },
    /**
     * 获取表格数据
     *
     * @author fengshuonan
     * @date 2022/5/8 15:18
     */
    datasource({ page, limit, where, orders }) {
      let result = DeviceLuoxunPulsationDataApi.findPage({ ...where, ...orders, pageNo: page, pageSize: limit });
      console.log(result);
      return result;
    },
    activated() {
      ['ch4Chart'].forEach((name) => {
        this.$refs[name].resize();
      });
    }
  }
};
</script>
